#include "spi.h"

void spi_Init(void){
	rcu_periph_clock_enable(RCU_GPIOA);
	// clk set
	gpio_mode_set(SPI_CLK_PORT,GPIO_MODE_AF,GPIO_PUPD_NONE,SPI_CLK_PIN);
	gpio_output_options_set(SPI_CLK_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_MAX, SPI_CLK_PIN);
  gpio_af_set(SPI_CLK_PORT,GPIO_AF_5,SPI_CLK_PIN);
	// sda set
	gpio_mode_set(SPI_MOSI_PORT,GPIO_MODE_AF,GPIO_PUPD_NONE,SPI_MOSI_PIN);
	gpio_output_options_set(SPI_MOSI_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_MAX, SPI_MOSI_PIN);
	gpio_af_set(SPI_MOSI_PORT,GPIO_AF_5,SPI_MOSI_PIN);

	rcu_periph_clock_enable(RCU_SPI0);
		spi_parameter_struct sps;
    spi_struct_para_init(&sps);
    sps.device_mode = SPI_MASTER; //????
    sps.frame_size = SPI_FRAMESIZE_8BIT;
    sps.clock_polarity_phase = SPI_CK_PL_LOW_PH_1EDGE;
    sps.nss = SPI_NSS_SOFT;
    sps.prescale = SPI_PSC_32;
    sps.endian = SPI_ENDIAN_MSB;
    spi_init(SPI0, &sps);
    //spi_nss_internal_high(spix);
    spi_enable(SPI0);
}

void SPI0_write_byte(uint8_t data) {
    while(RESET == spi_i2s_flag_get(SPI0, SPI_FLAG_TBE)) {};
    spi_i2s_data_transmit(SPI0, data);
    while(spi_i2s_flag_get(SPI0, SPI_FLAG_TRANS) == 1);
}

uint8_t SPI0_read_byte() {
    while(RESET == spi_i2s_flag_get(SPI0, SPI_FLAG_TBE)) {};
    spi_i2s_data_transmit(SPI0, 0x00);
    while(RESET == spi_i2s_flag_get(SPI0, SPI_FLAG_RBNE)) {};
    return spi_i2s_data_receive(SPI0);
}

